package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import com.tanhua.service.MovementApi;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;


@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    /**
     * 发布动态
     * @param movement
     */
    @Override
    public String publish(Movement movement) {
        //设置pid和当前毫秒值
        movement.setPid(idWorker.getNextId("chenchu"));
        movement.setCreated(System.currentTimeMillis());
        //将动态保存到数据库
        mongoTemplate.save(movement);

        timeLineService.saveTimeLine(movement.getUserId(), movement.getId());

        return movement.getId().toHexString();

    }


    /**
     * 查询指定用户的动态详情
     * @param page
     * @param pagesize
     * @param userId
     * @return
     */
    @Override
    public PageResult pageMovements(Integer page, Integer pagesize, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1);
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));;
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        PageResult pageResult = new PageResult(page, pagesize, 0L, movements);
        return pageResult;
    }

    /**
     * 查询用户好友
     * @param id
     * @return
     */
    @Override
    public PageResult getFriend(Long id) {
        Criteria criteria = Criteria.where("userId").is(id);
        Query query = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        PageResult pageResult = new PageResult();
        pageResult.setItems(friends);
        return pageResult;
    }

/*    *//**
     * 通过id查询出自己能看到的动态
     * @param id
     * @return
     *//*
    @Override
    public PageResult getFriendMovements(Long id, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("friendId").is(id);
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize);
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        PageResult pageResult = new PageResult(page, pagesize, 0L, movementTimeLines);
        return pageResult;

    }*/

    /**
     * 根据动态id获取动态
     * @param movementIds
     * @return
     */
    @Override
    public List<Movement> getMovements(List<ObjectId> movementIds, Integer page, Integer pagesize) {

        /*
        第一种方法：循环
        List<Movement> list = new ArrayList<>();
        Criteria criteria = null;
        Query query = null;
        for (ObjectId movementId : movementIds) {
            criteria = Criteria.where("_id").is(movementId);
            query = Query.query(criteria);
            Movement one = mongoTemplate.findOne(query, Movement.class);
            list.add(one);
        }*/

        Criteria criteria = Criteria.where("_id").in(movementIds).and("state").is(1);
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return list;
    }

    //查询用户可以看的动态id
    @Override
    public List<MovementTimeLine> getVisible(Long id) {
        Criteria criteria = Criteria.where("friendId").is(id);
        Query query = Query.query(criteria);
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        return movementTimeLines;
    }

    //获取集合中的动态
    @Override
    public List<Movement> selectMovement(List<Long> collect) {
        //redis中的参数值的pid字段的数值
        Criteria criteria = Criteria.where("pid").in(collect).and("state").is(1);
        Query query = Query.query(criteria);
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return list;
    }

    //随机推送pagesize条的动态
    @Override
    public List<Movement> randomMovement(Integer counts) {
        //第一个参数指明去那张表进行操作
        //第二个参数是随机获取几条数据
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(counts));
        //方法参数,TypedAggregation:生成策略,        movement.class:生成后的参数用什么泛型接受
        AggregationResults<Movement> movements = mongoTemplate.aggregate(aggregation, Movement.class);
        //返回获随机获取到的参数
        return movements.getMappedResults();
    }

    @Override
    public Movement getById(ObjectId objectId) {
        Query query = Query.query(Criteria.where("_id").is(objectId));
        Movement one = mongoTemplate.findOne(query, Movement.class);
        return one;
    }

    @Override
    public PageResult getMovementsState(Integer page, Integer pagesize, Long userId, String state) {
        Criteria criteria = new Criteria();
        if (userId != null) {
            criteria.where("userId").is(userId);
        }
        if (StringUtils.isNotEmpty(state)) {
            criteria.where("state").is(state);
        }
        Query query = Query.query(criteria);
        long count = mongoTemplate.count(query, Movement.class);
        query.skip((page - 1) * pagesize).limit(pagesize);
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return new PageResult(page, pagesize, count, list);
    }

    @Override
    public void updateMovementState(Movement movement, int state) {
        Query query = Query.query(Criteria.where("_id").is(movement.getId()));
        Update update = new Update();
        update.set("state", state);
        mongoTemplate.updateFirst(query, update, Movement.class);
    }


}